from flask import render_template, current_app, session, request, jsonify, g

from info import redis_store, create_app
from info.models import User, News, Category
from info.modules.index import index_blu
from info.utils.comment import user_login_data
from info.utils.response_code import RET

#  TODO """ 获得新闻首页内容"""
@index_blu.route('/news_list')
def news_list():
    # print("111111+++")
    # 获取参数
    request_list = request.args
    cid = request_list.get("cid", 1)
    page = request_list.get("page",1)
    per_page = request_list.get("per_page",6)

    # print(page,per_page,cid)

    # 检验参数
    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误")
    # print("22222++++++2222")


    # 查询数据并进行分页
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    # 将 TODO filterss 列表的数据进行分包操作  将生成的新闻按时间倒序排列然后再
    # 进行分页操作   pafinate最后的  flase 是阻止打印错误信息
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        # TODO items 显示当前页的所有数据
        items = paginate.items
        # print(len(items))
        # 获取到总页数
        total_page = paginate.pages
        # print(total_page)
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据查询失败")
    # print("333333+++++333333")

    news_dict_li = []
    for news1 in items:
        news_dict_li.append(news1.to_basic_dict())
    # print("444444++++44444")

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li

         }
        # 返回数据
    return jsonify(errno = RET.OK,errmsg = "OK",data = data )


@index_blu.route('/')
@user_login_data
def index():
    # # 向redis中保存一个值 name itcast
    # # redis_store.set("name", "susu")
    # user_id  = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # TODO 从数据库中取出点击量排名前六的新闻数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    # 这是一个列表生成式,可以理解为   if news_list  for循环  else  为[]
    for news in  news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    # 获取新闻分类的数据
    categories = Category.query.all()
    # 定义一个空列表,用于保存数据
    categories_dicts = []

    for category in categories:
        categories_dicts.append(category.to_dict())


    data = {
        "user": user.to_dict() if user else None,
        "click_news_list" : click_news_list,
        "categories": categories_dicts
    }

    return render_template('news/index.html',data = data )




    # return render_template('news/index.html')

@index_blu.route('/favicon.ico')
def favicon():
    """flask里面内置的一种方法，显示查找静态文件的方法"""
    return current_app.send_static_file('news/favicon.ico')
